package com.sinosoft.sinopay.apiservice.batchpay.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sinosoft.sinocloud.platform.base.SinoBaseService;
import com.sinosoft.sinocloud.platform.common.util.DateUtil;
import com.sinosoft.sinocloud.platform.common.util.XStreamComponent;
import com.sinosoft.sinopay.api.common.dto.pay.PaymentInfoDetailDTO;
import com.sinosoft.sinopay.api.pay.service.BatchpayApiService;
import com.sinosoft.sinopay.apiservice.batchpay.dto.PayTradeMainDTO;
import com.sinosoft.sinopay.apiservice.batchpay.dto.TLPayReqBody;
import com.sinosoft.sinopay.apiservice.batchpay.dto.TLPayReqInfo;
import com.sinosoft.sinopay.apiservice.batchpay.dto.TLPayReqTransDetail;
import com.sinosoft.sinopay.apiservice.batchpay.dto.TLPayReqTransDetails;
import com.sinosoft.sinopay.apiservice.batchpay.dto.TLPayReqTransSum;
import com.sinosoft.sinopay.apiservice.batchpay.dto.TLPayReqXml;
import com.sinosoft.sinopay.apiservice.batchpay.dto.TLPayResBody;
import com.sinosoft.sinopay.apiservice.batchpay.dto.TLPayResInfo;
import com.sinosoft.sinopay.apiservice.batchpay.dto.TLPayResRetDetail;
import com.sinosoft.sinopay.apiservice.batchpay.dto.TLPayResXml;
import com.sinosoft.sinopay.apiservice.batchpay.util.AmountTransUtil;
import com.sinosoft.sinopay.apiservice.batchpay.util.PropertiesUtils;
import com.sinosoft.sinopay.paytrade.dto.PaymentTradeBatchDTO;
import com.sinosoft.sinopay.paytrade.dto.PaymentTradeReqDTO;
import com.sinosoft.sinopay.paytrade.facade.PaymentTradeFacadeService;
import com.sinosoft.sinopay.paytrade.facade.PaymentTradeQueryFacadeService;

/**
 * 【 支付批量接口实现 】
 *
 * @author chenzhiheng
 * @version V1.0
 * @date 16/12/27
 */
@Service
public class BatchpayApiServiceImpl extends SinoBaseService implements BatchpayApiService{

//    private String fileName = "";
//    private String appPath = null;
//    private File filePath ;

    @Autowired
    private PaymentTradeQueryFacadeService paymentTradeQueryFacadeService;

    @Autowired
    private PaymentTradeFacadeService paymentTradeFacadeService;

    @Override
    public void batchPay(String bankCode) {
        List<PaymentTradeReqDTO> paymentTradeReqDTOList = paymentTradeQueryFacadeService.queryAllPayOrderBatchesOfDay(bankCode);
        try {
            if(submitData(paymentTradeReqDTOList,bankCode)){
                logger.info("交易成功!");
            }
        } catch (DocumentException e) {
            e.printStackTrace();
            logger.error("数据提交失败!");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            logger.error("找不到路径");
        }
    }


    /**
     * 数据提交的公共方法
     *
     * @return 布尔值（true--提交成功, false--提交失败）
     */
    public boolean submitData(List<PaymentTradeReqDTO> paymentTradeReqList, String bankCode) throws DocumentException, FileNotFoundException {
        boolean tReturn = false;
        List<PaymentTradeReqDTO> paymentBatchList = new ArrayList<PaymentTradeReqDTO>(); //支付批次订单数据
        paymentBatchList = paymentTradeReqList;
        if (paymentBatchList.size() == 0) throw new NullPointerException("无发送银行数据！");
        //获取当日所有需要走批量的数据
        PaymentTradeReqDTO paymentBatch ;
        String payFlag = null;
        String batchNo = DateUtil.getCurrentDate("yyyyMMdd");
        //循环所有支付批次信息
        for(int i = 0 ; i < paymentBatchList.size(); i++){
            paymentBatch = paymentBatchList.get(i);
            //获取操作类型
            payFlag = paymentBatch.getPayFlag();
            String reqBatchNo = paymentBatch.getReqBatchNo();
            List<PaymentInfoDetailDTO> paymentMainList = new ArrayList<PaymentInfoDetailDTO>(); //支付交易数据
            if("3333".equals(bankCode)){
                paymentMainList = paymentTradeQueryFacadeService.queryAllPayTransInfoForBatchNo(paymentBatch.getReqBatchNo());
            }else{
                paymentMainList = paymentTradeQueryFacadeService.queryAllPayTransInfoForDay(bankCode);
            }
            List<PayTradeMainDTO> payTradeMainDTOList = new ArrayList<PayTradeMainDTO>();
            
            if("S4".equals(payFlag)){
                //判断当日是否需要发送批量任务
                if(paymentMainList.size() == 0){
                    return false;
                }else if(paymentBatch.getResultCode() == null){ //判断当日是否发过盘
                    for(int j = 0; j < paymentMainList.size() ; j++){
                        if(paymentMainList.get(j).getReturnCode() == null && !"2".equals(paymentMainList.get(j).getPayState())) { //判断当日是否发过盘
                            //写入List中
                        	PayTradeMainDTO payTradeMain = new PayTradeMainDTO();
                            payTradeMain.setAccountName(paymentMainList.get(j).getAccountName());
                            payTradeMain.setAccountNo(paymentMainList.get(j).getAccountNo());
                            payTradeMain.setPayAmount(paymentMainList.get(j).getPayAmount());
                            payTradeMain.setPayStatus("2");//已发至批量
                            payTradeMainDTOList.add(payTradeMain);

                            //修改交易支付关系表中数据
                            PaymentTradeReqDTO paymentRela = new PaymentTradeReqDTO();//支付批次与交易关系数据
                            paymentRela.setBatchNo(reqBatchNo);
                            paymentRela.setState("1");
                            paymentRela.setSendTime(DateUtil.getCurrentDate());
                            int resultRela = paymentTradeFacadeService.modifyPaymentInfo(paymentRela);
                            if(resultRela < 1){
                                throw new DocumentException("修改交易支付表数据失败!");
                            }
                        }
                    }
                    if("3333".equals(bankCode)){
                        //通联支付--收
                        handTLPayDateS(payTradeMainDTOList,paymentBatch);
                        tReturn = true;
                        return tReturn;
                    }
                }
            }else{
                //TODO 代付
                if("3333".equals(bankCode)){
                    //通联支付--付
                    handTLPayDateF(payTradeMainDTOList,paymentBatch);
                    tReturn = true;
                    return tReturn;
                }
            }
            BigDecimal batchSumAmount = new BigDecimal("0");
            batchSumAmount = batchSumAmount.add(paymentBatch.getSumAmount());
            //修改交易总表数据发盘日期和状态
            PaymentTradeBatchDTO tradePaymentBatch=paymentTradeQueryFacadeService.queryPaySumInfoByBatchNo(paymentBatch.getReqBatchNo());//批量支付总表数据
            tradePaymentBatch.setSendTime(DateUtil.getCurrentDate());
            tradePaymentBatch.setState("1");
            int resultInfo = paymentTradeFacadeService.modifyBatchPaymentInfo(tradePaymentBatch);
            if(resultInfo != 1){
                throw new DocumentException("修改交易总表数据失败!");
            }
            PaymentTradeReqDTO paymentBatchs = new PaymentTradeReqDTO();//交易批次信息表数据
            paymentBatchs.setReqBatchNo(paymentBatch.getBatchNo());
            paymentBatchs.setSendTime(DateUtil.getCurrentDate());
            int resultBatch = paymentTradeFacadeService.modifyTransOrderBatchInfo(paymentBatchs);
            if(resultBatch < 1){
                throw new DocumentException("修改批次信息数据失败!");
            }
        }
        String fileName = paymentTradeQueryFacadeService.queryOfferFileNameByOfferPayChannelId(Integer.parseInt(bankCode));
        if(fileName == null){
            batchNo= batchNo+"0001";
        }else{
            batchNo= batchNo+"0002";
        }
        //非通联支付生成FTP数据和上传数据
        if(!"3333".equals(bankCode)) {
//            getFtpRes(bankCode, payFlag,batchNo);
        }
        //新增一条报盘记录表数据
        PaymentTradeBatchDTO paymentTradeBatch = new PaymentTradeBatchDTO();
        paymentTradeBatch.setOfferDate(DateUtil.getCurrentDate());
        paymentTradeBatch.setPayBatchNo(batchNo);
        paymentTradeBatch.setOfferFile(fileName);
        paymentTradeBatch.setOfferFileStatus("1");
        paymentTradeBatch.setCreateDate(DateUtil.getCurrentDate());
        int resultTradeBatch = paymentTradeFacadeService.addOfferRecordData(paymentTradeBatch);
        if(resultTradeBatch != 1){
            throw new DocumentException("添加报盘记录表数据失败!");
        }
        if (!tReturn)
            logger.debug("Save sucessful");
        else
            logger.debug("Save failed");

        return tReturn;
    }

    /**
     * 通联支付数据处理实现
     *@return
     */
    public void handTLPayDateS(List<PayTradeMainDTO> payTradeMainDTOList ,PaymentTradeReqDTO paymentBatch) {
        try {
            PaymentTradeReqDTO paymentMainTrade = new PaymentTradeReqDTO();
            PaymentTradeReqDTO paymentMain = new PaymentTradeReqDTO();
            TLPayReqXml tlPayReqXml = new TLPayReqXml();
            TLPayReqInfo tlPayReqInfo = new TLPayReqInfo();
            TLPayReqTransDetails tlPayReqTransDetails = new TLPayReqTransDetails();
            TLPayReqBody tlPayReqBody = new TLPayReqBody();
            TLPayReqTransSum tlPayReqTransSum = new TLPayReqTransSum();
            String tPath = "/config/allinpayConfig.properties";
            Properties properties = PropertiesUtils.readProperties(tPath);
            tlPayReqInfo.setTRX_CODE(properties.getProperty("TRX_CODE_S")); // 报文头
            tlPayReqInfo.setVERSION(properties.getProperty("VERSION"));
            tlPayReqInfo.setLEVEL(properties.getProperty("LEVEL")); // 处理级别
            tlPayReqInfo.setDATA_TYPE(properties.getProperty("DATA_TYPE"));
            tlPayReqInfo.setUSER_NAME(properties.getProperty("USER_NAME"));
            tlPayReqInfo.setUSER_PASS(properties.getProperty("USER_PASS"));
            Date date = new Date();
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddhhmmss");
            String dateNow = df.format(date);
            tlPayReqInfo.setREQ_SN(String.valueOf(System.currentTimeMillis())); // 交易流水号 商户ID+系统时间//properties.getProperty("REQ_SN")//String.valueOf(System.currentTimeMillis())//1486863585995
            tlPayReqInfo.setSIGNED_MSG(""); // 签名信息
            tlPayReqXml.setINFO(tlPayReqInfo);

            tlPayReqTransSum.setBUSINESS_CODE(properties.getProperty("BUSINESS_CODE"));
            tlPayReqTransSum.setMERCHANT_ID(properties.getProperty("MERCHANT_ID"));
            tlPayReqTransSum.setSUBMIT_TIME(dateNow);
            tlPayReqTransSum.setTOTAL_ITEM(String.valueOf(payTradeMainDTOList.size()));
            if(paymentBatch.getSumAmount()==null||"".equals(paymentBatch.getSumAmount())){
            	throw new Exception("总金额不能为空");
            }
            AmountTransUtil aAmountTransUtil = new AmountTransUtil();
            System.out.println("money="+paymentBatch.getSumAmount());
            String money = aAmountTransUtil.transAmount(paymentBatch.getSumAmount());
            tlPayReqTransSum.setTOTAL_SUM(money);
            tlPayReqBody.setTRANS_SUM(tlPayReqTransSum);
            List<TLPayReqTransDetail> tlPayReqTransDetailList = new ArrayList<TLPayReqTransDetail>();
            for (int i = 0; i < payTradeMainDTOList.size(); i++) {
                TLPayReqTransDetail tlPayReqTransDetail = new TLPayReqTransDetail();
                tlPayReqTransDetail.setACCOUNT_NAME(payTradeMainDTOList.get(i).getAccountName());
                tlPayReqTransDetail.setACCOUNT_NO(payTradeMainDTOList.get(i).getAccountNo());
                tlPayReqTransDetail.setACCOUNT_PROP(Integer.parseInt(properties.getProperty("ACCOUNT_PROP")));
                tlPayReqTransDetail.setACCOUNT_TYPE(properties.getProperty("ACCOUNT_TYPE"));
                //TODO
                String tAmount = aAmountTransUtil.transAmount(payTradeMainDTOList.get(i).getPayAmount());
                tlPayReqTransDetail.setAMOUNT(tAmount);
                tlPayReqTransDetail.setBANK_CODE("403");
                tlPayReqTransDetail.setBANK_NAME("");
                tlPayReqTransDetail.setCITY("");
                tlPayReqTransDetail.setCURRENCY("NBK");//properties.getProperty("CURRENCY")
                tlPayReqTransDetail.setCUST_USERID("");
                tlPayReqTransDetail.setE_USER_CODE("");
                tlPayReqTransDetail.setID("");
                tlPayReqTransDetail.setID_TYPE("");
                tlPayReqTransDetail.setPROTOCOL("");
                tlPayReqTransDetail.setPROTOCOL_USERID("");
                tlPayReqTransDetail.setPROVINCE("");
                tlPayReqTransDetail.setREMARK("");
                tlPayReqTransDetail.setSETTACCT("");
                tlPayReqTransDetail.setSN((i + 1));
                tlPayReqTransDetail.setTEL("");
                tlPayReqTransDetailList.add(tlPayReqTransDetail);
            }
            tlPayReqBody.setTRANS_DETAILS(tlPayReqTransDetailList);
            tlPayReqXml.setBODY(tlPayReqBody);
            XStreamComponent xstream = new XStreamComponent();
            xstream.processAnnotations(new Class[]{TLPayReqBody.class, TLPayReqInfo.class, TLPayReqTransDetail.class,
                     TLPayReqTransSum.class, TLPayReqXml.class, TLPayResBody.class
                    , TLPayResInfo.class, TLPayResRetDetail.class,  TLPayResXml.class});
            String reqXml = "<?xml version=\"1.0\" encoding=\"GBK\"?>" + xstream.toXML(tlPayReqXml).replace("__", "_");//properties.getProperty("Package_Header")
            logger.info("请求报文：" + reqXml.toString());
            String url = properties.getProperty("SERVER_URL");
            HandTLPayS handTLPayS = new HandTLPayS();
            String signData = handTLPayS.isFront(reqXml,false,url);
            //解析返回报文
            TLPayResXml response = (TLPayResXml) xstream.fromXML(signData);
            String returnCode = response.getINFO().getRET_CODE();
            List<TLPayResRetDetail> tlResList ;
            if(returnCode!=null && returnCode.equals("0000")){
                tlResList = response.getBODY().getRET_DETAILS();
                for(int i = 0; i < tlResList.size() ; i++){
                    for(int j = 0; j < tlPayReqTransDetailList.size(); j++){
                        if(tlResList.get(i).getSN() == tlPayReqTransDetailList.get(j).getSN()) {
                            paymentMain.setBatchNo(paymentBatch.getReqBatchNo());
                            paymentMain.setReturnTime(DateUtil.getCurrentDate());
                            paymentMain.setResultCode(tlResList.get(i).getRET_CODE());
                            paymentMain.setResultDesc(tlResList.get(i).getERR_MSG());
                            int resultMain = paymentTradeFacadeService.modifyPaymentInfo(paymentMain);
                            if (resultMain < 1) {
                                throw new Exception("修改支付交易数据关联表失败!");
                            }

                            paymentMainTrade.setBatchNo(paymentBatch.getReqBatchNo());
                            paymentMainTrade.setResultCode(tlResList.get(i).getRET_CODE());
                            paymentMainTrade.setResultDesc(tlResList.get(i).getERR_MSG());
                            int resultMainTrade = paymentTradeFacadeService.modifyTransePayRelate(paymentMainTrade);
                            if (resultMainTrade < 1) {
                                throw new Exception("修改支付交易数据失败!");
                            }
                        }
                    }
                }
            }else{
                logger.error("通联批扣请求有误!");
            }
        } catch(Exception ex) {
            ex.printStackTrace();
            logger.error("通联批扣出错");
        }
    }
    
    /**
     * 通联支付数据处理实现
     *@return
     */
    public void handTLPayDateF(List<PayTradeMainDTO> payTradeMainDTOList ,PaymentTradeReqDTO paymentBatch) {
    	AmountTransUtil aAmountTransUtil = new AmountTransUtil();
        try {
            PaymentTradeReqDTO paymentMainTrade = new PaymentTradeReqDTO();
            PaymentTradeReqDTO paymentMain = new PaymentTradeReqDTO();
            TLPayReqXml tlPayReqXml = new TLPayReqXml();
            TLPayReqInfo tlPayReqInfo = new TLPayReqInfo();
            TLPayReqTransDetails tlPayReqTransDetails = new TLPayReqTransDetails();
            TLPayReqTransDetail tlPayReqTransDetail = new TLPayReqTransDetail();
            TLPayReqBody tlPayReqBody = new TLPayReqBody();
            TLPayReqTransSum tlPayReqTransSum = new TLPayReqTransSum();
            String tPath = "/config/allinpayConfig.properties";
            Properties properties = PropertiesUtils.readProperties(tPath);
            tlPayReqInfo.setTRX_CODE(properties.getProperty("TRX_CODE_F")); // 报文头
            tlPayReqInfo.setVERSION(properties.getProperty("VERSION"));
            tlPayReqInfo.setLEVEL(properties.getProperty("LEVEL")); // 处理级别
            tlPayReqInfo.setDATA_TYPE(properties.getProperty("DATA_TYPE"));
            tlPayReqInfo.setUSER_NAME(properties.getProperty("USER_NAME"));
            tlPayReqInfo.setUSER_PASS(properties.getProperty("USER_PASS"));
            Date date = new Date();
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddhhmmss");
            String dateNow = df.format(date);
            tlPayReqInfo.setREQ_SN(properties.getProperty("REQ_SN") + dateNow); // 交易流水号 商户ID+系统时间
            tlPayReqInfo.setSIGNED_MSG(""); // 签名信息
            tlPayReqXml.setINFO(tlPayReqInfo);

            tlPayReqTransSum.setBUSINESS_CODE(properties.getProperty("BUSINESS_CODE"));
            tlPayReqTransSum.setMERCHANT_ID(properties.getProperty("MERCHANT_ID"));
            tlPayReqTransSum.setSUBMIT_TIME(dateNow);
            tlPayReqTransSum.setTOTAL_ITEM(paymentBatch.getTradeNum().toString());
            tlPayReqTransSum.setTOTAL_SUM(paymentBatch.getSumAmount().toString());
            tlPayReqBody.setTRANS_SUM(tlPayReqTransSum);

            List<TLPayReqTransDetail> tlPayReqTransDetailList = new ArrayList<TLPayReqTransDetail>();
            for (int i = 0; i < payTradeMainDTOList.size(); i++) {
                tlPayReqTransDetail.setACCOUNT_NAME(payTradeMainDTOList.get(i).getAccountName());
                tlPayReqTransDetail.setACCOUNT_NO(payTradeMainDTOList.get(i).getAccountNo());
                tlPayReqTransDetail.setACCOUNT_PROP(0);
                tlPayReqTransDetail.setACCOUNT_TYPE(properties.getProperty("ACCOUNT_TYPE"));
                String tAmount = aAmountTransUtil.transAmount(payTradeMainDTOList.get(i).getPayAmount());
                tlPayReqTransDetail.setAMOUNT(tAmount);
                tlPayReqTransDetail.setBANK_CODE("0105");
                tlPayReqTransDetail.setBANK_NAME("");
                tlPayReqTransDetail.setCITY("");
                tlPayReqTransDetail.setCURRENCY(properties.getProperty("CURRENCY"));
                tlPayReqTransDetail.setCUST_USERID("");
                tlPayReqTransDetail.setE_USER_CODE("");
                tlPayReqTransDetail.setID("");
                tlPayReqTransDetail.setID_TYPE("");
                tlPayReqTransDetail.setPROTOCOL("");
                tlPayReqTransDetail.setPROTOCOL_USERID("");
                tlPayReqTransDetail.setPROVINCE("");
                tlPayReqTransDetail.setREMARK("");
                tlPayReqTransDetail.setSETTACCT("");
                tlPayReqTransDetail.setSN((i + 1));
                tlPayReqTransDetail.setTEL("");
                tlPayReqTransDetailList.add(tlPayReqTransDetail);
            }
            tlPayReqBody.setTRANS_DETAILS(tlPayReqTransDetailList);
            tlPayReqXml.setBODY(tlPayReqBody);
            XStreamComponent xstream = new XStreamComponent();
            xstream.processAnnotations(new Class[]{TLPayReqBody.class, TLPayReqInfo.class, TLPayReqTransDetail.class,
                     TLPayReqTransSum.class, TLPayReqXml.class, TLPayResBody.class
                    , TLPayResInfo.class, TLPayResRetDetail.class, TLPayResXml.class});
            String reqXml = properties.getProperty("Package_Header") + xstream.toXML(tlPayReqXml).replace("__", "_");
            System.out.println("请求报文：\n" + reqXml);
            HandTLPayF handTLPayF = new HandTLPayF();
            String signData = handTLPayF.signMsg(reqXml);
            String url = properties.getProperty("SERVER_URL");
            boolean flag = false;
            String strResp = handTLPayF.sendXml(signData, url, flag);
            //解析返回报文
            TLPayResXml response = (TLPayResXml) xstream.fromXML(strResp);
            String returnCode = response.getINFO().getRET_CODE();
            List<TLPayResRetDetail> tlResList ;
            if(returnCode!=null && !returnCode.equals("0000")){
                tlResList = response.getBODY().getRET_DETAILS();
                for(int i = 0; i < tlResList.size() ; i++){
                    for(int j = 0; j < tlPayReqTransDetailList.size(); j++){
                        if(tlResList.get(i).getSN() == tlPayReqTransDetailList.get(j).getSN()) {
                            paymentMain.setBatchNo(paymentBatch.getBatchNo());
                            paymentMain.setReturnTime(DateUtil.getCurrentDate());
                            paymentMain.setResultCode(tlResList.get(i).getRET_CODE());
                            paymentMain.setResultDesc(tlResList.get(i).getERR_MSG());
                            int resultMain = paymentTradeFacadeService.modifyPaymentInfo(paymentMain);
                            if (resultMain < 1) {
                                throw new Exception("修改支付交易数据关联表失败!");
                            }

                            paymentMainTrade.setBatchNo(paymentBatch.getBatchNo());
                            paymentMainTrade.setResultCode(tlResList.get(i).getRET_CODE());
                            paymentMainTrade.setResultDesc(tlResList.get(i).getERR_MSG());
                            int resultMainTrade = paymentTradeFacadeService.modifyTransePayRelate(paymentMainTrade);
                            if (resultMainTrade < 1) {
                                throw new Exception("修改支付交易数据失败!");
                            }

                        }
                    }
                }
            }else{
                logger.error("通联批扣请求有误!");
            }
        } catch(Exception ex) {
            ex.printStackTrace();
            logger.error("通联批扣出错");
        }
    }
    
    /**
     * 生成FTP数据和上传数据
     *@return
     */
    /*private boolean getFtpRes(String bankCode,String payFlag,String batchNo) throws FileNotFoundException {
        boolean result = true;

        String tPath = "/config/bankConfig.properties";
        Properties properties = PropertiesUtils.readProperties(tPath);
        String ip = properties.getProperty(bankCode+"_ServiceIp");
        int port = Integer.parseInt(properties.getProperty(bankCode+"_DK"));
        String user = properties.getProperty(bankCode+"_User");
        String password = properties.getProperty(bankCode+"_Password");
        // 获取文件名和文件路径
        fileName = BankNameHandler.getNameByCode(bankCode, payFlag,batchNo).lastIndexOf(".")+ ".xml";
        String rootPath = this.getClass().getResource("/").getPath().toString();
        String basePath = rootPath+"sendToBank/"+payFlag; //生成文件的路径
        String subPath = DateUtil.getCurrentDate("yyyyDDmm");    // 子文件夹
        filePath = new File(basePath, subPath);
        logger.debug("filePath: " + filePath + " | bankCode: " + bankCode + " | busstype : " + payFlag);
        filePath.mkdirs();

        if (!writeBankFile(new File(filePath, fileName))) {
            return false;
        }
        // 转换xml
        String zipFileName = fileName.substring(0, fileName.lastIndexOf(".")) + ".txt";
        if (!xmlTransform(new File(filePath, fileName), new File(filePath, zipFileName),properties.getProperty("_XslPath"))) {
            return false;
        }

        //String tFileUploadPath = payBankConfInfo.getSendFtpPath();
        String tFileUploadPath = properties.getProperty("_FileUploadPath");
        if (tFileUploadPath == null || "".equals(tFileUploadPath)) {
            throw new NullPointerException("没有配置Ftp服务器上传路径信息......请配置......");
        }

        InputStream inputStream = new FileInputStream(new File(zipFileName));
        if (!uploadToFtp(user,password, (tFileUploadPath+DateUtil.getCurrentDate("yyyyMMdd")).trim(),zipFileName ,inputStream,ip,port)) {
            return false;
        }
        return result;
    }*/


    /**
     * 上传文件
     * @param username   FTP登录帐号
     * @param password   FTP登录密码
     * @param cFtpAddress   FTP服务器保存目录
     * @param fileName   上传到FTP服务器后的文件名称
     * @param inputStream 待上传文件的名称（绝对地址）
     * @return
     */
    public boolean uploadToFtp(String username, String password, String cFtpAddress, String fileName, InputStream inputStream,String Ip,int port){
        boolean flag = false;
        FTPClient ftpClient = new FTPClient();
        ftpClient.setControlEncoding("UTF-8");
        try {
            //连接FTP服务器
            ftpClient.connect(Ip,port);
            //登录FTP服务器
            ftpClient.login(username, password);
            //是否成功登录FTP服务器
            int replyCode = ftpClient.getReplyCode();
            if(!FTPReply.isPositiveCompletion(replyCode)){
                return flag;
            }
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpClient.makeDirectory(cFtpAddress);
            ftpClient.changeWorkingDirectory(cFtpAddress);
            ftpClient.storeFile(fileName, inputStream);
            inputStream.close();
            ftpClient.logout();
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally{
            if(ftpClient.isConnected()){
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return flag;
    }

    /**
     * 生成送银行文件
     *
     * @param file
     * @return
     */
    /*private boolean writeBankFile(File file) {
        int i;
        PrintWriter out = null;
        try {
            logger.debug("Start creating file ......");
            logger.debug("File Name : " + file.getAbsolutePath());

            out = new PrintWriter(new FileWriter(file), true);
            out.println("<?xml version=\"1.0\" encoding=\"gbk\"?>");
            out.println("<?xml-stylesheet type=\\\"text/xsl\\\" href=\\\"BankDataFormat.xsl\"?>");
            out.println("");
            // 生成文件头信息
            out.println("<!--");
            out.println(" * <p>FileName: " + fileName + " </p>");
            out.println(" * <p>Description: 业务系统数据转银行系统文件 </p>");
            out.println(" * <p>Copyright: Copyright (c) 2002</p>");
            out.println(" * <p>Company: sinosoft </p>");
            out.println(" * @Author：Minim's WriteToFileBLS");
            out.println(" * @CreateDate：" + DateUtil.getCurrentDate());
            out.println("-->");
            out.println("");
            out.println("<BANKDATA>");
            out.println("<HEAD>");
            out.println("<BUSINO>"+79103800+"</BUSINO>");
            out.println("<FIZNO>"+05106+"</FIZNO>");
            out.println("<TRADENUM>"+paymentBatchList.size()+"</TRADENUM>");
            out.println("<SUMAMOUNT>"+batchSumAmount+"</SUMAMOUNT>");
            out.println("</HEAD>");
            for (i = 0; i < payTradeMainDTOList.size(); i++) {
                PayTradeMainDTO tpayTradeMainDTO = payTradeMainDTOList.get(i);
                Class c = PayTradeMainDTO.class;
                Field f[] = c.getDeclaredFields();
                out.println("  <ROW>");
                out.println(" <NUM>"+(i+1)+"</NUM> ");
                for (int elementsNum = 0; elementsNum < f.length; elementsNum++) {
                    out.print("    <" + f[elementsNum].getName() + ">");
                    if (f[elementsNum].getName().equals("PayAmount")) {
                        out.print((new DecimalFormat("0.00")).format(Double.parseDouble(tpayTradeMainDTO.getV(f[elementsNum].getName()))));
                    } else {
                        out.print(tpayTradeMainDTO.getV(f[elementsNum].getName()));
                    }
                    out.println("</" + f[elementsNum].getName() + ">");
                }
                out.println("  </ROW>");
                out.println("");
            }
            out.println("</BANKDATA>");
            out.println("");
            out.println("<!-- Create BankFile Success! -->");
            out.close();
        } catch (Exception e) {
            logger.error("Create File Error!");
            return false;
        }
        return true;
    }*/


    /**
     * Simple sample code to show how to run the XSL processor from the API.
     *
     * @throws
     */
    public boolean xmlTransform(File fSource, File fTarget,String xslPath) {
        FileInputStream input = null;
        InputStreamReader inputreader = null;
        FileOutputStream out = null;
        try {
            input = new FileInputStream(fSource);
            inputreader = new InputStreamReader(input);
            out = new FileOutputStream(fTarget);
            logger.debug("xslPath:" + xslPath);
            File fStyle = new File(xslPath);
            Source source = new StreamSource(inputreader);//生成的XML文件
            Result result = new StreamResult(out);// 需要生成的txt文件
            Source style = new StreamSource(fStyle); //格式文件  xsl
            // Create the Transformer
            TransformerFactory transFactory = TransformerFactory.newInstance();
            Transformer transformer = transFactory.newTransformer(style);
            // Transform the Document
            transformer.transform(source, result);
            logger.debug("Transform Success!");
            out.flush();
            input.close();
            inputreader.close();
            out.close();

            logger.debug("Transform Success!");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("WriteToFileBLS:SimpleTransform----Xml处理失败");
            return false;
        }

        return true;
    }

}
